//
//  BrrowMoneyController.m
//  DianDangDai
//
//  Created by bhf on 2017/12/14.
//  Copyright © 2017年 bhf. All rights reserved.
//

#import "BrrowMoneyController.h"
#import "BMCell.h"
#import "SDCycleScrollView.h"
#import "UIButton+WebCache.h"
@interface BrrowMoneyController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate,SDCycleScrollViewDelegate>
{
    NSString *_jklx;
    NSString *_jkje;
    NSString *_jkqx;
    NSString *_lxdh;
    NSString *_yzm;
    NSString *_imgUUID;
    NSString *_imgURL;
    NSString *_imgCode;
}
@property (nonatomic, strong) NSArray *imgArray;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSArray *placeholder;
@property (nonatomic, strong) NSArray *goodType;
@property (nonatomic, strong) NSMutableArray *array;

@end

@implementation BrrowMoneyController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self setupViews];
    [self getImage];
    [self requestData];

    self.imgArray = @[@"a1",@"a2",@"a3",@"a4",@"a5",@"a6"];
    self.titleArray = @[@"物品类别",@"借款金额",@"借款期限",@"联系电话",@"图形码",@"验证码"];
    self.placeholder = @[@"请选择申请的物品类型",@"请输入借款金额",@"请输入1~12月内整月期限",@"请输入联系电话",@"请输入图形码",@"请输入验证码"];
    self.goodType = @[@"汽车",@"房产",@"名表",@"钢材",@"标准件",@"手机靓号",@"电子产品",@"珠宝玉石",@"红木家具",@"贵金属首饰",@"其他"];
    // Do any additional setup after loading the view.
}

- (void)setupViews {
    self.submit.layer.cornerRadius = 22;
}

- (void)getImage {
    NSString *urlString = [NSString stringWithFormat:@"%@OPT=1011",API_LOGIN_URL_STRING];
    [[CDHttpHelper defaultCDHttpHelper] get:urlString params:nil success:^(id responseObj) {
        NSDictionary *dict = [responseObj objectFromJSONData];
        NSLog(@"%@",dict);
        _imgUUID = dict[@"randomId"];
        _imgURL = dict[@"img"];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    } showHUD:YES];
}

- (void)requestData {
    _array = [NSMutableArray array];
    NSString *urlString = [NSString stringWithFormat:@"%@OPT=1002",API_LOGIN_URL_STRING];
    [[CDHttpHelper defaultCDHttpHelper] get:urlString params:nil success:^(id responseObj) {
        NSDictionary *dict = [responseObj objectFromJSONData];
      
        for (NSDictionary *dic in dict[@"jiekuan"]) {
            
            [self.array addObject:dic[@"img"]];
        }
        
        [self setUpScrollView];
    } failure:^(NSError *error) {
        
    } showHUD:NO];
}

//第三方轮播图
- (void)setUpScrollView {
    
    SDCycleScrollView *cycleScrollView3 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 180) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
    cycleScrollView3.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
    cycleScrollView3.currentPageDotColor = [UIColor colorWithHex:@"#118cf8"];
    cycleScrollView3.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    cycleScrollView3.imageURLStringsGroup = _array;
    NSLog(@"%@",_array);
    
    [self.scrollView addSubview:cycleScrollView3];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *identifier;
    
    switch (indexPath.row) {
        case 0:
            identifier = @"bm_cell_I";
            break;
        case 1:
            identifier = @"bm_cell_II";
            break;
        case 2:
            identifier = @"bm_cell_II";
            break;
        case 3:
            identifier = @"bm_cell_II";
            break;
        case 4:
            identifier = @"bm_cell_III";
            break;
        case 5:
            identifier = @"bm_cell_III";
            break;
        default:
            break;
    }
    
    BMCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    cell.textField.delegate = self;
    cell.image.image = [UIImage imageNamed:_imgArray[indexPath.row]];
    cell.name.text = _titleArray[indexPath.row];
    cell.textField.placeholder = _placeholder[indexPath.row];
    cell.textField.tag = indexPath.row+100;
    switch (indexPath.row) {
        case 1:
            cell.label.text = @"元";
            cell.textField.keyboardType = UIKeyboardTypeNumberPad;
            break;
        case 2:
            cell.label.text = @"月";
            cell.textField.keyboardType = UIKeyboardTypeNumberPad;
            break;
        case 3:
            cell.label.hidden = YES;
            cell.textField.keyboardType = UIKeyboardTypeNumberPad;
            break;
        default:
            break;
    }
    
    if (indexPath.row == 4) {
        cell.button.tag = 104;
        [cell.button sd_setImageWithURL:[NSURL URLWithString:_imgURL] forState:UIControlStateNormal placeholderImage:nil options:SDWebImageRefreshCached];
    }
    
    if (indexPath.row == 5) {
        cell.button.tag = 105;
    }
    return cell;
}
#pragma mark - TextField Delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField.tag == 100) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        for (NSString *title in _goodType) {
            UIAlertAction *action = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                textField.text = action.title;
            }];
            [alert addAction:action];
        }
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:nil];
        return NO;
    } else {
        return YES;
    }
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    switch (textField.tag) {
        case 101:
            _jkje = textField.text;
            break;
        case 102:
            _jkqx = textField.text;
            break;
        case 103:
            _lxdh = textField.text;
            break;
        case 104:
            _imgCode = textField.text;
            break;
        case 105:
            _yzm = textField.text;
            break;
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return (SCREEN_HEIGHT-314)/6;
}

- (IBAction)tijiao:(UIButton *)sender {
    NSString *urlString = [NSString stringWithFormat:@"%@OPT=1002&jklx=%@&jkje=%@&jkqx=%@&lxdh=%@&yzm=%@",API_LOGIN_URL_STRING,_jklx,_jkje,_jkqx,_lxdh,_yzm];
    [[CDHttpHelper defaultCDHttpHelper] get:urlString params:nil success:^(id responseObj) {
        NSDictionary *dict = [responseObj objectFromJSONData];
        
        NSLog(@"%@",dict);
    } failure:^(NSError *error) {
        
    } showHUD:NO];
}



- (IBAction)getMessage:(UIButton *)sender {

    if (sender.tag == 104) {
        
        NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:4 inSection:0]; //刷新第0段第2行
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationNone];
        
    } else if (sender.tag == 105) {
        
        
        __block int timeout = 119; //倒计时时间
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
        
        dispatch_source_set_event_handler(_timer, ^{
            
            if(timeout<=0){ //倒计时结束，关闭
                
                dispatch_source_cancel(_timer);
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    //设置界面的按钮显示 根据自己需求设置
                    [sender setTitle:@"丨获取验证码" forState:0];
                   
                    sender.userInteractionEnabled = YES;
                });
                
            }else{
                
                //            int minutes = timeout / 60;
                
                int seconds = timeout % 120;
                
                NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    //设置界面的按钮显示 根据自己需求设置
                    
                    [sender setTitle:[NSString stringWithFormat:@"丨%@S后获取",strTime] forState:UIControlStateNormal];
                    
                    sender.userInteractionEnabled = NO;
                    
                });
                
                timeout--;
                
            }
            
        });
        
        dispatch_resume(_timer);
        
        NSString *urlString = [NSString stringWithFormat: @"%@OPT=1012&mobile=%@&cCode=%@&randomId=%@",API_LOGIN_URL_STRING,_lxdh,_imgCode,_imgUUID];
        
        NSLog(@"%@",urlString);
        [[CDHttpHelper defaultCDHttpHelper] get:urlString params:nil success:^(id responseObj) {
            NSDictionary *dict = [responseObj objectFromJSONData];
            NSLog(@"%@",dict);
            [self.view makeToast:dict[@"msg"]];
        } failure:^(NSError *error) {
            
        } showHUD:YES];
    }
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
